<template>
  <div class="h-[12px]"></div>
  <div class="detail-style" id="scrollContainer" @scroll="handleScroll">
    <div id="top"></div>
    <Flow ref="FlowRef"></Flow>
    <div
      class="flex"
      :class="handleType != 'view' ? 'pb-42' : 'pb-30'"
      ref="scrollContainer"
    >
      <div class="flex-1" style="width: 80%">
        <el-card class="box-card mt-2" shadow="never">
          <div id="spuInfo" class="flex justify-between items-center">
            <div class="header-title">SPU信息</div>
          </div>
          <SpuInfo
            ref="spuInfoRef"
            v-model="form"
            @initsku="initsku"
            @sync="syncName"
          ></SpuInfo>
        </el-card>

        <el-card class="box-card mt-2 mb-[10px]" shadow="never">
          <div id="multiattribute" class="header-title">多属性设置</div>
          <MultiAttribute
            ref="multiAttributeRef"
            v-model="form"
            :spu="form.spu"
            @change="changeAttribute"
          >
          </MultiAttribute>
        </el-card>

        <div id="SKUOffsetTop"></div>

        <el-affix :offset="95">
          <el-tabs
            v-model="activeName"
            type="card"
            class="px-2 pt-2 bg-[var(--base-dialog-bg-color)] border-b border-solid border-[#e4e7ed]"
            @tab-click="handleTag"
          >
            <el-tab-pane
              v-for="(item, index) in goods_sku_list"
              :key="index"
              :label="item.sku"
              :name="item.sku"
            >
              <template #label>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="item.sku_cn_title"
                  placement="top-start"
                >
                  {{ item.sku || item.custom_sku }}
                </el-tooltip>
                <span v-if="item.sales_status == 4" class="base-red-color"
                  >({{ item.sales_status_text }})</span
                >
              </template>
            </el-tab-pane>
          </el-tabs>
        </el-affix>
        <el-card
          class="box-card card-affix"
          shadow="never"
          v-if="form.goods_sku?.length"
          v-loading="skuLoading"
        >
          <div class="flex justify-between items-center h-[44px]">
            <div id="SKUMaintain" class="font-bold">SKU维护</div>
          </div>
          <div class="card-affix-tab">
            <el-card class="box-card card-content-line" shadow="never">
              <div id="SKUInfo" class="flex justify-between items-center">
                <div class="header-title">产品基础信息</div>
              </div>
              <SellInfo v-model="current_sku" class="line"></SellInfo>
            </el-card>
            <el-card class="box-card mt-2 card-content-line" shadow="never">
              <div id="peopleInfo" class="flex justify-between items-center peopleInfo">
                <div class="header-title">处理人员信息</div>
              </div>
              <PeopleInfo ref="peopleInfoRef" v-model="current_sku"></PeopleInfo>
            </el-card>
            <el-card class="box-card mt-2 card-content-line" shadow="never">
              <div
                id="weightSizeInfo"
                class="flex justify-between items-center weightSizeInfo"
              >
                <div class="header-title">产品重量尺寸</div>
              </div>
              <weightSizeInfo
                ref="weightSizeInfoRef"
                v-model="current_sku"
                class="line"
              ></weightSizeInfo>
            </el-card>
            <el-card class="box-card mt-2 card-content-noline border-card" shadow="never">
              <!-- 产品图片设置 -->
              <div id="pictureId" class="pictureId">
                <Picture
                  ref="pictureRef"
                  v-model="current_sku.goods_sku_gallery"
                  :currentIndex="current_index"
                >
                </Picture>
              </div>
            </el-card>
            <el-card
              class="box-card mt-2 flex w-full tabs-style card-content-noline border-card"
              shadow="never"
            >
              <Remark v-model="current_sku.goods_sku_remark" id="SKURemark">
                <template #header>
                  <div class="flex justify-between">
                    <div class="header-title mt-[8px]">备注信息</div>
                  </div>
                </template>
              </Remark>
            </el-card>

            <el-card
              class="box-card mt-2 w-full tabs-content-border certificate-card"
              shadow="never"
            >
              <Certificate
                ref="CertificateRef"
                v-model="current_sku.goods_sku_certificate"
              >
                <template #header>
                  <div id="certificateFile" class="header-title mb-2">证书/文件</div>
                </template>
              </Certificate>
            </el-card>

            <el-card class="box-card mt-2 w-full tabs-content-border" shadow="never">
              <recommend
                v-model="current_sku.goods_sku_recommended_platform"
                :info="{
                  packing_size_cm: current_sku.packing_size_cm,
                  package_weight: current_sku.gross_weight_g,
                }"
              >
                <template #header>
                  <div id="platformSite" class="header-title">推荐平台/站点</div>
                </template>
              </recommend>
            </el-card>

            <el-card
              class="box-card mt-2 tabs-content-border"
              shadow="never"
              id="GeneralInfoRef"
            >
              <el-tabs
                v-model="generalactive"
                type="card"
                class="header-mb0"
                @tab-change="changeTab($event, index)"
              >
                <el-tab-pane label="供应商信息" name="Supplier" />
                <el-tab-pane label="商品描述" name="2" />
                <el-tab-pane label="组合SKU" name="4" v-if="current_sku.is_combination" />
                <el-tab-pane label="产品头程运费设置" name="8"> </el-tab-pane>
                <el-tab-pane label="渠道SKU" name="5" />
                <el-tab-pane label="拿样记录" name="6" />
                <el-tab-pane
                  label="关联辅料"
                  name="7"
                  v-if="current_sku.sku_product_type != 2"
                />
                <el-tab-pane
                  v-if="!current_sku.is_relation_sku"
                  label="切换SKU"
                  name="9"
                />
              </el-tabs>
              <div class="card-body">
                <div class="header-title inline-block">SKU综合信息</div>
                <!-- 供应商信息 -->
                <div v-if="generalactive == 'Supplier'">
                  <Supplier
                    ref="supplierRef"
                    v-model="current_sku.goods_sku_supplier"
                    :custom_sku="current_sku.custom_sku"
                    :sku="current_sku.sku"
                    :index="current_index"
                    :info="{
                      custom_sku: current_sku.custom_sku,
                      sku: current_sku.sku,
                      sku_product_type: current_sku.sku_product_type,
                      dev_status: current_sku.dev_status,
                      sku_id: current_sku.id,
                      spu_category: form.spu_category,
                      is_dangerous: form.is_dangerous,
                      brand_name: current_sku.goods_sku_sales_info?.brand_name,
                    }"
                    v-if="generalactive == 'Supplier'"
                    @queryDetail="queryDetail('edit')"
                  >
                  </Supplier>
                </div>

                <!-- 商品描述 -->
                <div v-if="generalactive == '2'">
                  <Ddescribe
                    ref="DdescribeRef"
                    v-model="current_sku.goods_sku_description"
                  >
                  </Ddescribe>
                </div>

                <!-- 组合SKU -->
                <div v-if="generalactive == '4'">
                  <GroupSku
                    ref="GroupSkuRef"
                    v-model="current_sku.goods_sku_combination_sku"
                  >
                    <template #title>
                      <div class="mr-10 text-xl font-bold">
                        组合类型：{{
                          current_sku.combined_sources == 1
                            ? "开发组合"
                            : current_sku.combined_sources == 2
                            ? "销售组合"
                            : current_sku.combined_sources == 3
                            ? "拆包组合"
                            : ""
                        }}
                      </div>
                    </template>
                  </GroupSku>
                </div>

                <!-- 产品头程运费设置 -->
                <div v-if="generalactive == '8'">
                  <HeadFreight
                    ref="headFreightRef"
                    v-model="current_sku.goods_sku_head_freight"
                    :info="{
                      sku: current_sku.sku,
                      sku_id: current_sku.id,
                      gross_weight_g: current_sku.gross_weight_g,
                      packing_size_cm: current_sku.packing_size_cm,
                      goods_sku_supplier: current_sku.goods_sku_supplier,
                      exchange_rate: exchange_rate,
                    }"
                  ></HeadFreight>
                </div>

                <!-- 渠道SKU -->
                <ChannelSku
                  ref="ChannelSkuRef"
                  :custom_sku="current_sku.custom_sku"
                  v-if="generalactive == '5'"
                >
                </ChannelSku>

                <!-- 拿样记录 -->
                <Sample ref="SampleRef" v-if="generalactive == '6'"> </Sample>

                <!-- 关联辅料 -->
                <Ingredient
                  class="border border-t-0 py-2 px-2"
                  ref="IngredientRef"
                  v-model="current_sku.goods_sku_accessories"
                  :custom_sku="current_sku.custom_sku"
                  :sku="current_sku.sku"
                  v-if="generalactive == '7'"
                >
                </Ingredient>

                <SwitchSKU
                  v-model="current_sku.goods_sku_relation"
                  :current_sku="current_sku.sku"
                  v-if="generalactive == '9'"
                >
                </SwitchSKU>
              </div>

              <div id="bottom" ref="bottomRef"></div>
            </el-card>
          </div>
        </el-card>
      </div>
      <div class="sidebar">
        <el-affix :offset="affixtab ? 85 : 85">
          <div class="broadside w-52 mr-1.5 px-6">
            <div
              :class="[
                'broadside-item cursor-pointer',
                item.name == scrollPosition.activeModule ? 'active' : '',
              ]"
              v-for="(item, index) in filteredSKUItems"
              :key="index"
              @click="scrollTop(item.name, item.offset)"
            >
              {{ item.label }}
            </div>
          </div>
          <div
            class="mt-3 roll"
            :class="scrollPosition.isTopBottom == 'top' ? 'active' : ''"
            @click="scrollTop('top')"
          >
            <svg-icon
              class="text-[32px] text-[--base-color]"
              icon-class="roll-top"
            ></svg-icon>
          </div>
          <div class="mt-3 roll" @click="scrollTop('bottom')">
            <svg-icon
              class="text-[32px] text-[--base-color]"
              icon-class="roll-down"
            ></svg-icon>
          </div>
        </el-affix>
      </div>
      <div class="handle flex justify-center items-center py-4 fixed bottom-0 z-index">
        <div class="ml-10 mr-20">
          <el-button :type="handleType == 'view' ? 'primary' : ''" @click="back"
            >返回</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script name="TaskProductEdit" setup>
import SpuInfo from "../componentsDetail/SpuInfo.vue";
import SellInfo from "../componentsDetail/SellInfo.vue";
import PeopleInfo from "../componentsDetail/PeopleInfo.vue";
import MultiAttribute from "../componentsDetail/Attribute/index.vue";
import Picture from "../componentsDetail/Picture/index.vue";
import Remark from "../componentsDetail/Remark.vue";
import Certificate from "../componentsDetail/Certificate/index.vue";
import Flow from "../componentsDetail/Flow.vue";
import Ddescribe from "../componentsDetail/GeneralInfo/Ddescribe.vue";
import Supplier from "../componentsDetail/Supplier/index";
import GroupSku from "../componentsDetail/GeneralInfo/GroupSku.vue";
import ChannelSku from "../componentsDetail/GeneralInfo/ChannelSku.vue";
import Sample from "../componentsDetail/GeneralInfo/Sample/index";
import Ingredient from "../componentsDetail/GeneralInfo/Ingredient/index";
import recommend from "../componentsDetail/GeneralInfo/recommend/index";
import weightSizeInfo from "../componentsDetail/weightSizeInfo.vue";
import HeadFreight from "../componentsDetail/HeadFreight/index";
import { getOptions } from "@/api/index.js";
import { getDetail } from "../api";
import { computed, nextTick, reactive, ref, toRaw, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import useCommonStore from "@/store/modules/common";
import { storeToRefs } from "pinia";
const commonStore = useCommonStore();
const { languageOptions } = storeToRefs(commonStore);
import action from "@/utils/action.js";
import { queryBaseHeadFreightList } from "@/views/basics/reference-freight/api.js";
import { getCurrency } from "../api.js";
import { imageTypeText } from "../data.js";
import { product_identification_image, tag_style_image } from "@/utils/product/data.js";
import SwitchSKU from "../componentsDetail/GeneralInfo/SwitchSKU/index.vue";

const route = useRoute();
const router = useRouter();
const data = reactive({
  form: {
    spu: "",
    spu_category: [],
    is_notify: false,
    imitation_remark: "",
    is_notify: false,
    need_photo: 1,
    need_processing: 2,
    recommended_level: "",
    brand_id: "",
    brand_type: 1,
    authentication: [],
    spu_cn_title: "",
    spu_en_title: "",
    specifications: "",
    spu_status: 1,
    goods_source: 1,
    goods_sku: [],
    goods_spu_sales_info: {
      suggested_sales_price: "",
      currency: "",
      currency_id: "",
      warehouse_id: "",
      logistics_attributes: "",
      suggested_header_channel: "",
      custom_specification: [],
      competing_products_link: [""],
      spu_unit: "",
      packaging_method: "",
      plug_specification: "",
    },
    developer_id: "",
    purchaser_id: null,
    dev_reviewer_id: null,
    quality_inspector_id: null,
    img_processor_id: null,
    editor_id: null,
    goods_spu_prohibited_sales: [{ prohibited_platform: "", prohibited_site: "" }],
  },
  dialogVisible: false,
  errorMessage: "",
  handleType: "view",
  spuId: null,
  activeName: null,
  goods_spu_gallery: null,
  generalactive: "Supplier",
  sku: null,
  goods_sku_list: [],
  sku_product_type: null,
});
let {
  form,
  dialogVisible,
  errorMessage,
  handleType,
  spuId,
  activeName,
  goods_spu_gallery,
  generalactive,
  sku,
  goods_sku_list,
  sku_product_type,
} = toRefs(data);
const options = ref([]);
const creatSkuInfo = ref({});
provide("options", options);
provide("form", form);
provide("handleType", handleType);
provide("sku_product_type", sku_product_type);
provide(
  "creatSkuInfo",
  computed(() => {
    return creatSkuInfo.value;
  })
);
// 语言
const getLanguageList = async () => {
  commonStore.getLanguageList();
};
getLanguageList();

// 下拉数据
const fetchOption = async () => {
  const res = await getOptions({
    name: [
      "goods.GoodsSpu",
      "goods.GoodsSku",
      "goods.GoodsSkuSalesInfo",
      "goods.GoodsSkuSupplier",
      "goods.GoodsSkuAccessories",
      "goods.GoodsSkuSupplier",
      "gallery.GoodsSkuGalleryContents",
      "goods.GoodsSkuIdentificationProcessing",
      "goods.GoodsSkuCertificate",
    ],
  });
  options.value = res.data;
  initGallery();
};

// 初始化默认产品图片一个标签
const initGallery = (isreturn = false) => {
  let obj = {
    custom_tag: "默认",
    spu: form.spu,
    spu_category: form.value.spu_category,
    spu_cn_title: form.value.spu_cn_title,
    contents: [],
  };
  imageTypeText.forEach((element, e) => {
    obj.contents.push({
      label: element.label,
      image_type: element.value,
      showType: 0,
      values: [],
    });
  });
  if (isreturn) {
    return [obj];
  } else {
    goods_spu_gallery.value = [obj];
  }
};
initGallery();

const initGalleryContents = () => {
  let contents = [];
  imageTypeText.forEach((element, e) => {
    contents.push({
      label: element.label,
      image_type: element.value,
      showType: 0,
      values: [],
    });
  });
  return contents;
};

const CertificateRef = ref();
const FlowRef = ref();
const spuInfoRef = ref();
const queryDetail = async (type) => {
  try {
    const res = await getDetail({
      spuId: spuId.value,
      fromEdit: true,
    });
    nextTick(() => {
      let againData = res.data;
      againData.goods_sku = againData.goods_sku.map((i) => {
        i.goods_sku_gallery =
          i.goods_sku_gallery && i.goods_sku_gallery.length
            ? i.goods_sku_gallery.map((j) => {
                if (j.contents.length == 0) {
                  j.contents = initGalleryContents();
                } else {
                  j.contents = matchAndAdd(
                    goods_spu_gallery.value[0].contents,
                    j.contents
                  );
                  j.contents = j.contents.sort(
                    (a, b) => gallerySort(a.image_type) - gallerySort(b.image_type)
                  );
                }
                return j;
              })
            : initGallery(true);
        i.goods_sku_sales_info = i.goods_sku_sales_info || {
          brand_id: "",
          brand_type: 1,
          suggested_sales_price: "",
          currency: "",
          currency_id: 158,
          currency_name: "USD",
          warehouse_id: "",
          logistics_attributes: "",
          suggested_header_channel: "",
          custom_specification:
            handleType.value == "edit" ? [{ name: "", value: "" }] : [],
          competing_products_link: [""],
          spu_unit: "",
          packaging_method: "",
          plug_specification: "",
          goods_spu_prohibited_sales:
            handleType.value == "edit"
              ? [{ prohibited_platform: "", prohibited_site: "" }]
              : [],
        };
        if (handleType.value == "edit") {
          i.goods_sku_prohibited_sales = i.goods_sku_prohibited_sales?.length
            ? i.goods_sku_prohibited_sales
            : [
                {
                  platform_name: "",
                  site_code: "",
                  platform_id: "",
                },
              ];

          i.goods_sku_authentication = i.goods_sku_authentication?.length
            ? i.goods_sku_authentication
            : [
                {
                  country: [],
                  authentication_type: "",
                  authentication_name: "",
                },
              ];
        }

        i.goods_sku_remark = i.goods_sku_remark || {
          dev_remark: "",
          purchase_remark: "",
          inspection_remark: "",
          packaging_remark: "",
        };
        i.goods_sku_customs = i.goods_sku_customs || {
          cn_name: "",
          en_name: "",
          purpose: "",
          cn_material: "",
          en_material: "",
          declare_elements: "",
          customs_code: "",
          tax_rebate_rate: "",
          declare_price_usd: "",
          declare_unit: "",
          declare_link: "",
          declare_link_price_eur: "",
        };

        i.goods_sku_sales_info.custom_specification = i.goods_sku_sales_info
          .custom_specification?.length
          ? i.goods_sku_sales_info.custom_specification
          : [{ name: "", value: "" }];

        if (handleType.value == "view") {
          i.goods_sku_sales_info.custom_specification = i.goods_sku_sales_info.custom_specification.filter(
            (i) => i.name || i.value
          );
        }
        i.goods_sku_recommended_platform = i.goods_sku_recommended_platform || [];
        i.goods_sku_title =
          i.goods_sku_title &&
          i.goods_sku_title.map((j) => {
            j.show = true;
            return j;
          });
        i.main_img = i.attr_img;
        i.goods_sku_supplier = i.goods_sku_supplier
          .map((j) => {
            j.default_supplier = j.is_default_supplier;
            j.goods_sku_identification_processing = j.goods_sku_identification_processing.map(
              (k) => {
                if (k.product_identification == 3 || k.product_identification == 10) {
                  k.image = changeTagStyle(k.tag_style);
                } else if (k.product_identification) {
                  k.image = changeProductIdentification(k.product_identification);
                }
                return k;
              }
            );
            return j;
          })
          .sort((a, b) => {
            if (a.default_supplier === 1) return -1; // 将值为1的项放在前面
            if (b.default_supplier === 1) return 1; // 将值为1的项放在前面
            return 0;
          });

        i.old_clean_product_status = i.clean_product_status;
        i.old_sales_status = i.sales_status;

        if (i.goods_sku_relation_old?.goods_sku) {
          i.goods_sku_relation_old.is_change_sku = 1;
        }
        return i;
      });
      againData.goods_spu_specification = againData.goods_spu_specification?.length
        ? matchSpecification(againData.goods_spu_specification)
        : creatSpecification(againData.goods_sku[0].sku_specification);
      againData.is_push_to_saihe = 1;

      form.value = againData;

      activeName.value = sku.value || form.value.goods_sku[0]?.sku;
      goods_sku_list.value = form.value.goods_sku;
      form.value.is_dangerous = form.value.base_logistics_attributes?.is_dangerous;
      // handleResize();
      FlowRef.value.init();
      if (route.query?.roll) {
        setTimeout(() => {
          scrollTop(route.query.roll);
        }, 500);
      }
    });
  } catch (e) {
    throw Error(e);
  }
};

const matchAndAdd = (array1, array2) => {
  for (var i = 0; i < array1.length; i++) {
    var isDuplicate = false;
    for (var j = 0; j < array2.length; j++) {
      if (array1[i].image_type === array2[j].image_type) {
        isDuplicate = true;
        break;
      }
    }
    if (!isDuplicate) {
      array2.push(array1[i]);
    }
  }
  return array2;
};

const matchSpecification = (goods_spu_specification) => {
  const list = goods_spu_specification.map((spec) => {
    const updatedValues = [];

    spec.values.forEach((valueObj) => {
      const copyValue = { ...valueObj, show: true };
      updatedValues.push(copyValue);
    });

    const existingLanguageIds = new Set(
      updatedValues.map((valueObj) => valueObj.language_id)
    );

    if (languageOptions && languageOptions.value) {
      languageOptions.value.forEach((d) => {
        if (!existingLanguageIds.has(d.id)) {
          const copyValue = {
            language_id: d.id,
            language_name: d.name,
            language_code: d.short_name,
            is_relation_img: 0,
            show: d.id === 1 || d.id === 2 || d.id === 10,
            language_values: spec.values[0].language_values.map((v) => ({
              ...v,
              language_id: d.id,
              language_name: d.name,
              language_code: d.short_name,
              id: "",
              value: "",
            })),
          };
          updatedValues.push(copyValue);
        } else {
          updatedValues.forEach((valueObj) => {
            if (valueObj.language_id === d.id) {
              valueObj.show = d.id === 1 || d.id === 2 || d.id === 10;
            }
          });
        }
      });
    }

    spec.values = updatedValues.sort((a, b) => a.language_id - b.language_id);
    return spec;
  });

  return list;
};

const gallerySort = (type) => {
  if (type == 3) {
    return 0;
  } else {
    return type;
  }
};

// 修改spu 需要重置sku
const DdescribeRef = ref();
const initsku = () => {
  initGallery(options.value);
  DdescribeRef.value.getAttribute();
};

const back = () => {
  action.setGlobalState({
    changeMicoTabsPath: {
      type: "closeActiveTab",
    },
  });
};

// 编辑保存
// const peopleInfoRef = ref();
// const multiAttributeRef = ref();
// const weightSizeInfoRefs = ref([]);
// const peopleInfoRefs = ref([]);
// const pictureRefs = ref([]);
// const supplierRefs = ref();
// const headFreightRefs = ref();
// watch(
//   () => form.value?.goods_sku?.length,
//   (val) => {
//     updateSellInfoRefs();
//   }
// );
// const updateSellInfoRefs = () => {
//   weightSizeInfoRefs.value = form.value?.goods_sku?.map((_, index) =>
//     ref(`weightSizeInfoRef${index}`)
//   );
//   pictureRefs.value = form.value?.goods_sku?.map((_, index) => ref(`pictureRef${index}`));
//   supplierRefs.value = form.value?.goods_sku?.map((_, index) =>
//     ref(`supplierRef${index}`)
//   );
//   peopleInfoRefs.value = form.value?.goods_sku?.map((_, index) =>
//     ref(`peopleInfoRef${index}`)
//   );
//   headFreightRefs.value = form.value?.goods_sku?.map((_, index) =>
//     ref(`headFreightRef${index}`)
//   );
// };

// 锚点
const sideDataref = reactive({
  sideData: [
    {
      label: "SPU信息",
      name: "top",
    },
    {
      label: "多属性设置",
      name: "multiattribute",
    },
    {
      label: "SKU基础信息",
      name: "SKUInfo",
      offset: true,
    },
    {
      label: "SKU人员信息",
      name: "peopleInfo",
      offset: true,
    },
    {
      label: "SKU重量尺寸",
      name: "weightSizeInfo",
      offset: true,
    },
    {
      label: "SKU图片",
      name: "pictureId",
      offset: true,
    },
    {
      label: "SKU备注",
      name: "SKURemark",
      offset: true,
    },
    {
      label: "SKU证书/文件",
      name: "certificateFile",
      offset: true,
    },
    {
      label: "SKU推荐平台/站点",
      name: "platformSite",
      offset: true,
    },
    {
      label: "SKU综合信息",
      name: "GeneralInfoRef",
      offset: true,
    },
    {
      label: "保存/审核",
      name: "bottom",
      offset: true,
    },
  ],
});

const { sideData } = toRefs(sideDataref);

const filteredSKUItems = computed(() => {
  if (form.value.goods_sku?.length) {
    return sideData.value;
  } else {
    return sideData.value.slice(0, 3);
  }
});

const scrollPosition = reactive({
  top: 0,
  activeModule: "top",
  isTopBottom: "top",
});

const computedHeight = (e) => {
  if (e.currentTarget.scrollTop <= 1) {
    scrollPosition.isTopBottom = "top";
  } else if (
    e.currentTarget.scrollTop + e.currentTarget.clientHeight >=
    e.currentTarget.scrollHeight
  ) {
    scrollPosition.isTopBottom = "bottom";
  } else {
    scrollPosition.isTopBottom = "";
  }
};

const scrollContainer = ref();
const handleScroll = (event) => {
  let height = document.getElementById("scrollContainer").scrollTop;
  let heightSKu = document.querySelector(`#SKUOffsetTop`).offsetTop + 40;
  if (height >= heightSKu) {
    affixtab.value = form.value.goods_sku.length > 1 ? true : false;
  } else {
    affixtab.value = false;
  }
  scrollPosition.top = event.target.scrollTop;
  computedHeight(event);
  updateActiveModule();
};
const affixtab = ref(false);
const scrollTop = (selector, isOffset = false) => {
  nextTick(async () => {
    const element = document.querySelector(`#${selector}`);
    const offset = isOffset ? 45 : 0;
    if (element) {
      const height = element.offsetTop - offset;
      const container = document.querySelector("#scrollContainer");
      container.scrollTo({
        top: height,
        behavior: "smooth",
      });
    } else {
      console.warn(`Element with ID '${selector}' not found.`);
    }
  });
};

const updateActiveModule = () => {
  const containerTop = document.getElementById("scrollContainer").offsetTop + 45;
  const scrollPositionTop = scrollPosition.top;
  for (let i = 0; i < filteredSKUItems.value.length; i++) {
    let module = filteredSKUItems.value[i];
    const anchorElement = document.getElementById(module.name).offsetTop;
    const offset = module.offset ? -100 : 0;
    if (
      scrollPositionTop >= anchorElement + offset - containerTop &&
      (i === filteredSKUItems.value.length - 1 ||
        scrollPositionTop <
          (document.getElementById(filteredSKUItems.value[i + 1].name)?.offsetTop ||
            offset + 20) +
            offset -
            containerTop)
    ) {
      scrollPosition.activeModule = module.name;
      break;
    }
  }
};

//是否首次加载
const isFirstLoad = ref(true);
onMounted(async () => {
  isFirstLoad.value = false;
  fetchOption();
  // handleType.value = route.query?.type;
  await getBaseHeadFreightList();
  await getExchangeRate();
});

// 综合信息tab切换
const changeTab = async (val, index) => {
  generalactive.value = val;
};

const initPage = async () => {
  sku.value = route.query?.sku;
  if (route.query?.spuId || route.query?.productId) {
    spuId.value = route.query?.spuId || route.query?.productId;
    await queryDetail(route.query.type);
  }
};

const routeQuery = ref();
watch(
  router.currentRoute,
  (newRouter, oldRouter) => {
    if (newRouter.path == "/task/product/detail") {
      if (JSON.stringify(newRouter.query) !== "{}") {
        if (JSON.stringify(newRouter.query) != JSON.stringify(routeQuery.value)) {
          // handleType.value = route.query?.type;
          routeQuery.value = newRouter.query;
          initPage();
        }
        if (scrollPosition.top > 0) {
          setTimeout(() => {
            scrollTo(scrollPosition.top);
          }, 100);
        }
      }
    }
  },
  { immediate: true, deep: true }
);

// 跳转页面指定高度
const scrollTo = (height) => {
  const container = document.querySelector("#scrollContainer");
  container.scrollTo({
    top: height,
    behavior: "auto",
  });
};

const changeAttribute = (index = 0) => {
  activeName.value = form.value.goods_sku[index]?.sku;
  goods_sku_list.value = form.value.goods_sku;
};

const skuLoading = ref(false);
const handleTag = (val) => {
  skuLoading.value = true;
  setTimeout(() => {
    skuLoading.value = false;
  }, 1000);
};

// 处理多属性为空的情况
const creatSpecification = (sku_specification) => {
  const { attributes, header } = sku_specification;
  const specification_list = header.map((i) => {
    i.is_relation_img = 0;
    i.group_name = i.name;
    i.loading = false;
    i.show = true;
    i.valueName = "";
    i.values = [
      {
        language_name: "中文",
        language_id: 1,
        language_code: "zh-chs",
        show: true,
        name: i.name,
        language_values: [
          {
            language_id: 1,
            group: 1,
            spu_id: form.value.spu,
            name: i.name,
            value: attributes[i.key],
          },
        ],
      },
    ];
    return i;
  });
  return specification_list;
};

// 获取头程费用设置
const base_head_freight_list = ref([]);
const getBaseHeadFreightList = async () => {
  try {
    const res = await queryBaseHeadFreightList({
      pageSize: 100,
    });

    base_head_freight_list.value = res.data.map((item) => {
      const newId = item.id;
      item.base_head_freight_id = newId;
      delete item.id;
      return item;
    });
  } catch (e) {
    throw Error(e);
  }
};

provide("base_head_freight_list", base_head_freight_list);

const exchange_rate = ref("");
const getExchangeRate = async () => {
  try {
    const res = await getCurrency({
      currency: "USD",
    });
    exchange_rate.value = res.data[0]?.exchange_rate;
  } catch (e) {
    throw Error(e);
  }
};

// 同步SPU 名称到SKU
const syncName = () => {
  multiAttributeRef.value.inputFocus();
};

const changeProductIdentification = (val, row) => {
  return product_identification_image.get(val);
};

const changeTagStyle = (val, row) => {
  return tag_style_image.get(val);
};

const current_sku = computed(() => {
  return form.value.goods_sku.find((item) => item.sku === activeName.value);
});

const current_index = computed(() => {
  return form.value.goods_sku.findIndex((item) => item.sku === activeName.value);
});
</script>

<style lang="scss" scoped>
@import "../index.scss";
</style>
